package com.mixed.mixedserver.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.mixed.mixedserver.mapper.UserMapper;
import com.mixed.mixedserver.model.entity.User;
import com.mixed.mixedserver.model.vo.user.UserVO;
import com.mixed.mixedserver.service.UserService;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

/**
 * 用户 服务层实现。
 *
 * @author abluedog
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>  implements UserService{

    @Override
    public User login(User user) {
        User dbUser = this.queryChain().eq(User::getUserAccount, user.getUserAccount())
                .eq(User::getUserPassword, user.getUserPassword())
                .one();
        if (dbUser != null){
            StpUtil.login(dbUser.getId());
            // 在登录时缓存 user 对象
            StpUtil.getSession().set("user", BeanUtil.copyProperties(dbUser, UserVO.class));
            return dbUser;
        }
        return null;
    }

    @Override
    public UserVO getLoginUserVO(HttpServletRequest request) {
        if (StpUtil.isLogin()){
            return (UserVO) StpUtil.getSession().get("user");
        }
        return null;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public boolean register(User user) {
        //校验账号是否存在
        if (this.queryChain().eq(User::getUserAccount, user.getUserAccount()).one() == null){
            return this.save(user);
        }
        return false;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        if (StpUtil.isLogin()){
            return this.getById(StpUtil.getLoginIdAsLong());
        }
        return null;
    }

}
